
package dbConn;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class DBconn {
	static String urlString;
	static String nameString;
	static String password;
	static String dataBaseName;
	static String strURL;
	static Connection conn = null;
	static ResultSet rs = null;
	static PreparedStatement ps = null;

	public static void config(String path) {
		InputStream inputStream = DBconn.class.getClassLoader().getResourceAsStream(path);
		Properties properties = new Properties();
		try {
			properties.load(inputStream);
			nameString = properties.getProperty("db.username");
			password = properties.getProperty("db.password");
			dataBaseName = properties.getProperty("db.dataBaseName");
			strURL = properties.getProperty("db.url");
			urlString = "jdbc:mysql://" + strURL + "/" + dataBaseName
					+ "?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useSSL=false";
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	static {
		config("dbconn/jdbc.properties");
		System.out.println(urlString);
	}

	public static void init() {

		try {
			config("dbconn/jdbc.properties");

			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(urlString, nameString, password);

		} catch (SQLException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("init Conn failed");
			e.printStackTrace();
		}
	}
	
	public static String converDate(String str)
	{
		//String str = "五 2/21 19:02:59 2020";
		Pattern pDate = Pattern.compile(".*?([0-9].*)");
		Matcher mDate = pDate.matcher(str);
		
		String strDate = "";
		if(mDate.find())
		{	
			strDate = mDate.group(1);
		}
				
		SimpleDateFormat sdf; 
	    sdf = new SimpleDateFormat ("MM/dd HH:mm:ss yyyy"); 	

		Date date = null; //初始化date 
		try 
		{ 
			date = sdf.parse(strDate);  
		} 
		catch (ParseException e) 
		{ 
			e.printStackTrace(); 
		} 
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  // 设置日期格式
		String strTime = simpleDateFormat.format(date); 
		
		return strTime;
	}

	public static int insertSql(String sqlString, List<Object> list) {
		int i = 0;

		try {
			PreparedStatement pStatement = conn.prepareStatement(sqlString);
			int nPos = 1;
			for (Object object : list) {
				pStatement.setObject(nPos++, object);
			}

			i = pStatement.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("changeSql failed:" + sqlString);
			e.printStackTrace();
		}
		return i;
	}
	
	public static int insertSql(String sqlString, List<List<Object>> list, long max) {
		int i = 0;

		try {

			PreparedStatement pStatement = conn.prepareStatement(sqlString);
			conn.setAutoCommit(false); //使用事务的方式提交，提供效率
			max = 10;
			int nMaxNum = 0;
			long nListSize = list.size();
			do {
				for (int j = 0; j < max; j++) {
					int nPos = 1;
					for (Object object : list.get(nMaxNum)) {
						pStatement.setObject(nPos++, object);
					}
					pStatement.addBatch();
					nMaxNum++;	
					if (nMaxNum >= nListSize) {
						break;
					}
				}	
				pStatement.executeLargeBatch();	
				pStatement.clearBatch();
				if (nMaxNum >= nListSize) {
					conn.commit();
					break;
				}
			} while (true);
					
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("changeSql failed:" + sqlString);
			e.printStackTrace();
		}
		return i;
	}

	public static int updateSql(String sqlString, List<Object> list) {
		int i = 0;

		try {
			PreparedStatement pStatement = conn.prepareStatement(sqlString);
			int nPos = 1;
			for (Object object : list) {
				pStatement.setObject(nPos++, object);
			}
			i = pStatement.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("updateSql failed:" + sqlString);
			e.printStackTrace();
		}
		return i;
	}

	public static ResultSet querySql(String sqlString) {
		try {
			ps = conn.prepareStatement(sqlString);
			rs = ps.executeQuery(sqlString);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("querySql failed:" + sqlString);
			e.printStackTrace();
		}
		return rs;
	}

		//ResultSet rs, PreparedStatement ps, Connection conn
	public static void closeConn() 
	{
		try {
			rs.close();
			ps.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("closeConn failed");
			e.printStackTrace();
		}
	}
	
	public static String getLastOneInfo() throws SQLException 
	{
        fileInfo fileIf = new fileInfo();
        try 
        {
        	//init();
            PreparedStatement ps = (PreparedStatement) conn
                    .prepareStatement("select * from version_compare order by id DESC limit 1");
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
            	fileIf.setId(rs.getInt("id"));
            	fileIf.setFile_name(rs.getString("file_name"));
            	fileIf.setFile_path(rs.getString("file_path"));
            }
            //closeConn(rs, ps, conn);
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }

        //System.out.println(fileIf.toJson());
        return "";//fileIf.toJson();
    }
	
	public static void setAbiInfo(JSONObject json)
	{
		JSONArray arrayApi = new JSONArray();
	  	arrayApi.add(json);
        java.util.Iterator<Object> v = arrayApi.iterator();
        
		while (v.hasNext()) 
		{
            JSONObject ob = (JSONObject) v.next();        
            	try {
            		//init();
            		PreparedStatement ps = (PreparedStatement) conn
                    		.prepareStatement("INSERT INTO version_compare(file_name, file_path, base_size, compare_size, difference, modify_time, base_version, compare_version) values(?,?,?,?,?,?,?,?)");
                    ps.setString(1, ob.getString("filename"));
                    ps.setString(2, ob.getString("filepath"));
                    ps.setInt(3, ob.getIntValue("basesize"));
                    ps.setInt(4, ob.getIntValue("cmpsize"));
                    ps.setString(5, ob.getString("difference"));
                    ps.setString(6, ob.getString("modifyTime"));
                    ps.setString(7, ob.getString("baseversion"));
                    ps.setString(8, ob.getString("cmpversion"));
                    ps.executeUpdate();
					
				} 
            	catch (SQLException e) 
            	{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	
		}
	}
	
	public static void setFuncInfo(java.util.Iterator<Object> it)
	{	
    	//连接成功插入比对差异的json数据更新数据库
        
		while (it.hasNext()) {
            JSONObject ob = (JSONObject) it.next();        
            	try {
            		//init();
            		String time = "2020-06-18 8:00:00";
            		
                    PreparedStatement ps = (PreparedStatement) conn
                    		.prepareStatement("INSERT INTO version_compare(file_name, file_path, difference, modify_time,base_version,base_size) values(?,?,?,?,?,?)");
                    ps.setString(1, ob.getString("filename"));
                    ps.setString(2, ob.getString("filepath"));
                    ps.setString(3, ob.getString("function"));
                   
                    ps.setString(4, time);
                    ps.setString(5, "");
                    ps.setInt(6,0);
                    ps.executeUpdate();
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
	}
	
	public static void setRpmInfo( String rpmstr, String rpmstr_qpR, String pwd) throws SQLException 
	{	
		//info = rpmstr == null ? info : rpmstr;
		System.out.println("======>" + rpmstr_qpR);
		
		// find name from info
		Pattern pVersion = Pattern.compile(".*?Version.*?:(.*?)\n");
		Matcher mVersion = pVersion.matcher(rpmstr);
		
		Pattern pSize = Pattern.compile(".*?Size.*?:[ ]{0,}(.*?)\n");
		Matcher mSize = pSize.matcher(rpmstr);
		
		Pattern pSource = Pattern.compile(".*/(.*)");
		Matcher mSource = pSource.matcher(pwd);
		
		Pattern pSummary = Pattern.compile(".*?Summary.*?:(.*?)\n");
		Matcher mSummary = pSummary.matcher(rpmstr);
		
		Pattern pDate = Pattern.compile(".*?Build Date.*?:(.*?)\n");
		Matcher mDate = pDate.matcher(rpmstr);
		
		String base_version = "";
		if(mVersion.find())
		{	
			base_version = mVersion.group(1);
		}
		
		int base_size = 0;
		if(mSize.find())
		{	
			base_size = Integer.valueOf(mSize.group(1));
		}
		
		String file_name = "";
		if(mSource.find())
		{	
			file_name = mSource.group(1);
		}
		
		String introduction = "";
		if(mSummary.find())
		{	
			introduction = mSummary.group(1);
		}
		
		String rpmDate = "";
		if(mDate.find())
		{	
			rpmDate = converDate(mDate.group(1));
			System.out.println("lynn!" + mDate.group(1));
		}
	
		try 
        {
            //Connection conn = connMysql();
			init();
            PreparedStatement ps = (PreparedStatement) conn
            		.prepareStatement("INSERT INTO version_compare(introduction,base_version,file_name, file_path, base_size, modify_time, remark) values(?,?,?,?,?,?,?)");
            ps.setString(1, introduction);
            ps.setString(2, base_version);
            ps.setString(3, file_name);
            ps.setString(4, pwd);
            ps.setInt(5, base_size);
            ps.setString(6, rpmDate);
            ps.setString(7, rpmstr_qpR);
            System.out.println("333: "+ rpmstr_qpR);
    
            ps.executeUpdate();

        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
	}

}